import store from '@/store';
import axios from 'axios'
import { ElMessage } from 'element-plus'

// http://ec2-43-192-41-93.cn-northwest-1.compute.amazonaws.com.cn:9000
// axios.defaults.baseURL ='http://ec2-43-192-41-93.cn-northwest-1.compute.amazonaws.com.cn:9001/api' //后端开发环境地址
axios.defaults.baseURL = '/api'
axios.defaults.headers.post['Content-Type'] = 'application/json;charset=UTF-8';//配置请求头信息

// Add a request interceptor
axios.interceptors.request.use(
  function (config) {
    const token = localStorage.getItem('token')
    // const token = store.state.token;
    // config.headers.Authorization = `Bearer ${token}`
    config.headers.Authorization = `${token}`

    return config
  },
  function (error) {
    return Promise.reject(error)
  }
)

// Add a response interceptor
axios.interceptors.response.use(
  function (response) {
    // console.log('拦截器工作', store.state.token);
    // const { authorization } = response.headers
    // console.log('2222',localStorage.getItem('token'), 'token', authorization);
    // authorization && localStorage.setItem('token', authorization)
    return response
  },
  function (error) {
    if (error.response) {
      const { status } = error.response
      if (status === 401) {
        localStorage.removeItem('token');
        // ElMessage.error('登录过期，请重新登录')
        window.location.href = '#/login'
      }
    } else if (error.request) {
      // 请求发出去没有收到响应
      ElMessage.error({
        title: '错误',
        message: '请求超时，请刷新重试',
        position: 'bottom-right'
      })
    } else {
      // 在设置请求时发生了一些事情，触发了一个错误
      ElMessage.error({
        title: '错误',
        message: `请求失败：${error.message}`,
        position: 'bottom-right'
      })
    }

    return Promise.reject(error)
  }
)

export default axios
